package com.yuantong.xyerp.core.api.util;


import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONObject;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.Map;

/**
 * Created by Jianguo.Yin on 2021-07-22.
 */
public class SunStringUtil {

    /**
     * 品类
     */
    String comment = "/**\n" +
            " * 品类\n" +
            " */";




    /**
     * 下划线转驼峰
     * user_name  ---->  userName
     * userName   --->  userName
     *
     * @param underlineStr 带有下划线的字符串
     * @return 驼峰字符串
     */
    public static String toCamelCase(String underlineStr) {
        if (underlineStr == null) {
            return null;
        }
        // 分成数组
        char[] charArray = underlineStr.toCharArray();
        // 判断上次循环的字符是否是"_"
        boolean underlineBefore = false;
        StringBuffer buffer = new StringBuffer();
        for (int i = 0, l = charArray.length; i < l; i++) {
            // 判断当前字符是否是"_",如果跳出本次循环
            if (charArray[i] == 95) {
                underlineBefore = true;
            } else if (underlineBefore) {
                // 如果为true，代表上次的字符是"_",当前字符需要转成大写
                buffer.append(charArray[i] -= 32);
                underlineBefore = false;
            } else {
                // 不是"_"后的字符就直接追加
                buffer.append(charArray[i]);
            }
        }
        return buffer.toString();
    }

    public static void getMybatisBoot(String baseColumns) {
        System.out.println("=============================baseColumns===============================");
        System.out.println(baseColumns);
        getSharpProperties(baseColumns);
        getOnDuplicateKeyUpdate(baseColumns);
        getUpdateProperties(baseColumns);
        getIfSQL(baseColumns);
        getResults(baseColumns);

    }

    public static void getReplaceByJsonConst(String JsonConst) {
        JSONObject jsonObject = JSON.parseObject(JsonConst);
        //todo: Entry学习
        StringBuffer replace = new StringBuffer();
        // 想想 temp 长什么样就明白了   jsonObject.entrySet()
        for (Map.Entry<String, Object> temp :
                jsonObject.entrySet()) {
            JSONObject jsonObject1 = (JSONObject) temp.getValue();
            StringBuffer buffer = new StringBuffer();
            buffer.append(jsonObject1.get("name")).append("_").append(jsonObject1.get("value"));
            replace.append("\"").append(buffer.toString()).append("\"").append(",");
        }
        System.out.println(replace);
    }


    /**
     * 用于关联对象查询, 给整个对象起别名
     * @param tableAlias 针对 t_user 表, tableAlias可以传 u
     * @param columnPrefix 针对 t_user 表, columnPrefix 可以传 user_
     * return u.id AS user_id,
     */
    public static void getColumnAlias(String tableAlias, String columnPrefix, String baseColumns) {
        String[] columns = baseColumns.split(", ");
        StringBuilder sb = new StringBuilder();
        for (String column :
                columns) {
            sb.append(tableAlias).append(".").append(column).append(" AS ").append(columnPrefix).append(column).append(", ");
        }
        System.out.println("=============================getColumnAlias===============================");
        System.out.println(sb.toString());
    }

    public static void getOnDuplicateKeyUpdate(String baseColumns) {
        System.out.println("=============================getOnDuplicateKeyUpdate===============================");
        String midFix = " = values(";
        String suffix = "), ";
        String[] columns = baseColumns.split(", ");
        StringBuilder sb = new StringBuilder();
        for (String column :
                columns) {
            sb.append(column).append(midFix).append(column).append(suffix);
        }
        System.out.println(sb.toString());

    }

    /**
     *
     * @param baseColumns 随时复制替换 当前使用mapper的 base_columns
     * @return 得到 #{property}           得到 #{itemTemp.property} 这个在<foreach> 中使用, itemTemp可用idea查询批量替换
     */
    public static void getSharpProperties(String baseColumns) {
        System.out.println("=============================getProperties===============================");
        String prefix = "#{";
        String prefix2 = "#{itemTemp.";
        String suffix = "}, ";
        String[] properties = toCamelCase(baseColumns).split(", ");
        StringBuilder sb = new StringBuilder();
        StringBuilder sb2 = new StringBuilder();
        for (int i = 0; i < properties.length; i++) {
            sb.append(prefix).append(properties[i]).append(suffix);
            sb2.append(prefix2).append(properties[i]).append(suffix);
        }
        System.out.println(sb.toString());

        System.out.println("=============================getCollectionProperties===============================");
        System.out.println(sb2.toString());
    }

    /**
     * 该方法被另一个方法内部使用了
     * @param baseColumns 随时复制替换 当前使用mapper的 base_columns
     * @return 得到 column = #{property}
     */
    private static String[] getColumnsAndProperties(String baseColumns) {
        String prefix = "#{";
        String suffix = "}";
        String[] columns = baseColumns.split(", "); // 这是用mybaitis更新时候使用的
        String[] updateValue = toCamelCase(baseColumns).split(", ");
        for (int i = 0; i < updateValue.length; i++) {
            StringBuffer buf = new StringBuffer();
            buf.append(columns[i] + " = ").append(prefix).append(updateValue[i]).append(suffix);
            updateValue[i] = buf.toString();
        }
        return updateValue;
    }

    /**
     * @param baseColumns 随时复制替换 当前使用mapper的 base_columns
     * 得到 column = #{property}
     */
    public static void getUpdateProperties(String baseColumns) {
        System.out.println("===================================getUpdateProperties=========================");
        String prefix = "#{";
        String suffix = "}";
        String[] columns = baseColumns.split(", ");
        String[] updateValue = toCamelCase(baseColumns).split(", ");
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < updateValue.length; i++) {
            buf.append(columns[i] + " = ").append(prefix).append(updateValue[i]).append(suffix);
        }
        System.out.println(buf.toString().replaceAll("}", "}, "));

    }


    /**
     *
     * @param baseColumns 随时复制替换 当前使用mapper的 base_columns
     * 自动生成             @Result(property = "id",column = "id"),
     */
    public static void getResults(String baseColumns) {
        System.out.println("===============================getResults=============================");
        String prefix = "@Result(property = \"";
        String midfix = "\", column = \"";
        String suffix = "\")-";  // -用做分割符, split("-")
        String[] tableColumns = baseColumns.split(", "); // 这是用mybaitis更新时候使用的
        String[] camelColumns = toCamelCase(baseColumns).split(", ");
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < tableColumns.length; i++) {
            buf.append(prefix).append(camelColumns[i]).append(midfix)
                    .append(tableColumns[i]).append(suffix);
        }
        String[] results = buf.toString().split("-");
        for (String result :
                results) {
            System.out.println(result + ",");
        }
    }

    /**
     * 根据base_column 生成下面的mybatis语句
     *             <if test="realName != null">
     *                 real_name = #{realName}
     *             </if>
     * @param baseColumns base_calumns
     */
    public static void getIfSQL(String baseColumns) {
        System.out.println("===============================getIfSQL=============================");
        String prefix = "<if test=\"";
        String[] camelColumns = toCamelCase(baseColumns).split(", ");
        String midfix = " != null\">\n    ";    // 完美对齐
        String[] updateProperties = getColumnsAndProperties(baseColumns);
        String suffix = "\n</if>-";    // -划分
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < camelColumns.length; i++) {
            buf.append(prefix).append(camelColumns[i]).append(midfix)
                    .append(updateProperties[i] + ",")
                    .append(suffix);
        }
        String str = buf.toString();
        String[] split = str.split("-");
        for (String ifSql :
                split) {
            System.out.println(ifSql);
        }
    }


    /**
     * 日期时间 转 字符串
     *
     * @param temporal 需要转化的日期时间 LocalDateTime
     * @param pattern  时间格式
     * @return String 日期时间字符串，例如 2015-08-11 09:51:53
     */
    public static String dateToString(TemporalAccessor temporal, String pattern) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        return dateTimeFormatter.format(temporal);
    }

    /**
     * 日期时间字符串 转 日期时间(java.time.LocalDateTime)
     *
     * @param localDateTimeStr 日期时间字符串
     * @param pattern          日期时间格式 例如DATETIME_PATTERN
     * @return LocalDateTime 日期时间
     */
    public static LocalDateTime stringToLocalDateTime(String localDateTimeStr, String pattern) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        return LocalDateTime.parse(localDateTimeStr, dateTimeFormatter);
    }


}
